package com.jichangxiu.framework.interceptor;

import com.jichangxiu.common.utils.SqlUtils;
import com.jichangxiu.framework.utils.DynamicUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;

import java.sql.Statement;
import java.util.Collection;
import java.util.List;

@Slf4j
@Intercepts({@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}),
        @Signature(type = StatementHandler.class, method = "update", args = {Statement.class}),
        @Signature(type = StatementHandler.class, method = "batch", args = {Statement.class})})
public class MybatisLogSqlInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object target = invocation.getTarget();
        // 初始化行数为 1
        int lines = 1;
        // 默认状态为 "失败"
        String status = "失败";
        Object proceed = null;
        try {
            // 执行原始方法，并获取返回结果
            proceed = invocation.proceed();
            // 如果返回结果为集合，则统计行数
            if (proceed instanceof Collection<?>) {
                lines = ((List<?>) proceed).size();
            }
            // 执行成功，将状态设置为 "成功"
            status = "成功";
            return proceed;
        } catch (Exception ex) {
            log.error("【MybatisLogSqlInterceptor】当前使用的数据源为【" + DynamicUtils.currentSource() + "】执行数据库操作异常", ex);
            return proceed;
        } finally {
            // 打印日志
            log.debug("\u001B[38;5;220m\r\n【MybatisLogSqlInterceptor】当前使用的数据源为：【" + DynamicUtils.currentSource() + "】\r\n【MybatisLogSqlInterceptor】SQL：【" + SqlUtils.getMyBatisPlusSql(target) + "】\r\n【MybatisLogSqlInterceptor】状态：【" + status + "】\r\n【MybatisLogSqlInterceptor】耗时：【" + (System.currentTimeMillis() - startTime) + "】\r\n【MybatisLogSqlInterceptor】结果：【" + lines + "】\u001B[0m");
        }
    }

}
